<template>
  <div class="login-modal-content">
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      label-width="80px"
      @submit.prevent="handleLogin"
      @keyup.enter="handleLogin"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="请输入用户名"
          :prefix-icon="UserIcon"
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          :prefix-icon="Lock"
          show-password
        />
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
        <el-link type="primary" href="#" class="forgot-password">忘记密码？</el-link>
      </el-form-item>

      <el-form-item class="button-group">
        <el-button
          type="primary"
          :loading="isLoading"
          @click="handleLogin"
          class="login-button"
        >
          {{ isLoading ? "登录中..." : "登录" }}
        </el-button>
        <el-button
          type="default"
          @click="showRegisterModal"
          class="register-button"
        >
          注册账号
        </el-button>
      </el-form-item>

      <el-form-item v-if="loginError">
        <el-alert
          :title="loginError"
          type="error"
          :closable="false"
          show-icon
        />
      </el-form-item>

      <div class="register-link">
        <span>还没有账号？</span>
        <el-link type="primary" @click="showRegisterModal">立即注册</el-link>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { useAuthStore } from "@/stores/auth";
import type { LoginForm, User } from "@/types/auth";
import type { FormInstance, FormRules } from "element-plus";
import { User as UserIcon, Lock } from "@element-plus/icons-vue";

// 定义组件属性和事件
defineProps<{
  visible: boolean;
}>();

const emit = defineEmits<{
  close: [];
  "login-success": [user: User];
  "show-register": [];
}>();

// 获取认证状态管理器
const authStore = useAuthStore();

// 响应式状态
const isLoading = computed(() => authStore.isLoading);
const loginError = computed(() => authStore.error);

// 表单引用
const loginFormRef = ref<FormInstance>();

// 表单数据
const loginForm = reactive<LoginForm>({
  username: "",
  password: "",
  rememberMe: true,
});

// Element UI 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
  ],
};

// 清除错误信息
const clearErrors = () => {
  authStore.clearError();
};

// 显示注册模态框
const showRegisterModal = () => {
  emit("show-register");
};

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    await loginFormRef.value.validate();
    
    clearErrors();

    // 使用状态管理器进行登录
    const result = await authStore.login(
      loginForm.username,
      loginForm.password,
      loginForm.rememberMe,
    );

    if (result.success) {
      // 触发成功事件
      emit("login-success", authStore.user!);

      // 关闭模态框
      emit("close");

      // 重置表单
      resetLoginForm();
    }
  } catch (error: unknown) {
    // Validation error or API error
    console.error("Login error:", error);
  }
};

// 重置表单
const resetLoginForm = () => {
  loginForm.username = "";
  loginForm.password = "";
  loginForm.rememberMe = true;
};
</script>

<style lang="scss" scoped>
@use "../styles/variables" as *;
@use "../styles/mixins" as *;

.login-modal-content {
  padding: 20px;
}

.forgot-password {
  margin-left: auto;
}

.button-group {
  .el-form-item__content {
    display: flex;
    gap: 12px;
  }
}

.login-button {
  flex: 1;
}

.register-button {
  flex: 1;
}

.register-link {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
  color: var(--el-text-color-regular);
  
  .el-link {
    margin-left: 4px;
  }
}

// Element UI 样式覆盖
:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-input__wrapper) {
  border-radius: var(--el-border-radius-base);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px var(--el-color-primary);
}

:deep(.el-button--primary) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  
  &:hover {
    background-color: var(--el-color-primary-light-3);
    border-color: var(--el-color-primary-light-3);
  }
}

:deep(.el-alert) {
  border-radius: var(--el-border-radius-base);
}

:deep(.el-checkbox__label) {
  color: var(--el-text-color-primary);
}

:deep(.el-link) {
  color: var(--el-color-primary);
  
  &:hover {
    color: var(--el-color-primary-light-3);
  }
}
</style>
